/* Description: 目录遍历测试
 * Author: zhouhui
 * Release Date: 2014-09-07
 * Modify log: 
 */ 

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>

static int list_dir(const char *);



/* argv1 dir path */
int main(int argc, char **argv)
{
    if (list_dir(argv[1]) == -1 )
    {
        return 1;
    }
    return 0;
}

static int list_dir(const char * dir_path)
{   
    DIR * dir;
    dir = opendir(dir_path);
    if (dir == NULL)
    {
        char err_msg[512] = {0};
        strcpy(err_msg, "opendir->");
        strcat(err_msg, dir_path );
        perror(err_msg);
        return -1;
    }
 
    struct dirent * dep; 
    while ( (dep = readdir(dir)) )
    {
        if ( dep->d_name[0] == '.' || strcmp(dep->d_name,"..") == 0 )
            continue;

        char tmp_dir[255] = {0};
        switch (dep->d_type) {
        case 8:
            printf("file: %s/%s\n", dir_path, dep->d_name);
            break;
        case 10:
            printf("link: %s/%s\n", dir_path, dep->d_name);
            break;
        case 4:
            strncpy(tmp_dir, dir_path, strlen(dir_path));
            strncat(tmp_dir, "/",1);
            strncat(tmp_dir, dep->d_name,  strlen(dep->d_name));
            printf("dir: %s\n", tmp_dir);

            if (list_dir(tmp_dir) == -1)
            {
                printf("Err: list_dir %s\n",dep->d_name);
                return -1;
            }
            break;
        default:
            printf("unknown type: %s\n", dep->d_name);
            break;
        }
    }

    return 0;
}
